var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/mui';

//设置跨域访问
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();

});

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
//  注册接口
router.get('/reg',function (req,res) {
	var username = req.query.username;
	var pwd = req.query.pwd;
	var images = req.query.images;
	console.log('username:'+username);
	  var data = {
        code: 0,
        msg: 'success'
    }
	   MongoClient.connect(DB_CONN_STR, function(err, db) {
	   	    if(err){
	   	     data.code = -1;
            data.msg = err;
              res.send(data);
	   	    }else {
	   	    	  var coll = db.collection('users');
	   	    	   coll.insertOne({username:username,password:pwd,images:images});
                res.send(data);
	   	    }
	  
	   })

})

//   登录接口
router.get('/login',function (req,res) {
    var username = req.query.username;
    var password = req.query.pwd;
    console.log(password);
    var data = {
        code: 0,
        msg: 'success'
    }
    MongoClient.connect(DB_CONN_STR, function(err, db) {
        if(err){
            data.code = -1;
            data.msg = err+'连接数据库失败';
            res.send(data);
        }else {
            var coll = db.collection('users');
            var obj = {
                username:username,
                password:password
            }
           coll.find(obj).toArray(function (err,arr) {
			   if (err) {
			       data.code = -2;
			       data.msg = err +'没有查找到数据';
                   console.log(err);

               }else {
			        data.code = 0;
			        data.msg = '登录成功'
			   }
               res.send(data);
           })

        }

    })
})

//router.get('/')




module.exports = router;
